package com.trade.system.security;

import com.trade.module.base.entity.Resource;
import com.trade.module.base.service.ResourceService;
import com.trade.module.base.service.RoleService;
import com.trade.common.utils.Constants;
import com.trade.module.base.vo.RoleVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Class Description:资源角色缓存
 *
 * @Version v1.0 2017/4/22 11:38
 * @JDK version 1.8.0_51
 * @Author zfb
 */
@Component
public class UrlCache {
    @Autowired
    private RoleService roleService;

    @Autowired
    private ResourceService resourceService;

    private HashMap<String, List<String>> urlRoles=new HashMap<>();

    HashMap<String, List<String>> getUrlRoles() {
        return this.urlRoles;
    }

    public void setUrlRoles(HashMap<String, List<String>> urlRoles) {
        this.urlRoles = urlRoles;
    }

    public List<String> getUrlRoles(String key) {
        return urlRoles.get(key);
    }

    /**
     * 将URL可访问的角色放入urlRoles中
     * Maps the Url as key and List<String> as the value.
     */
    void loadUrlRoles(){
        //查出角色可访问的URL,并且按照URL做为key，角色集合做为值的方式存储角色资源访问权限
        List<RoleVo> roleVoList = roleService.findRoleAndResource();
        String dbUrl;
        if (null != roleVoList){
            for (RoleVo roleVo : roleVoList){
                List<Resource> resList = roleVo.getResourceList();
                if (null != resList){
                    for(Resource res : resList){
                        if (Constants.RESOURCE_LEVEL_5.equalsIgnoreCase(res.getResLevel())){
                            dbUrl = res.getResUrl();
                            if(this.urlRoles.containsKey(dbUrl)){
                                List<String> roles=this.urlRoles.get(dbUrl);
                                roles.add(roleVo.getRoleCode());
                            }else{
                                List<String> roles=new ArrayList<>();
                                roles.add(roleVo.getRoleCode());
                                this.urlRoles.put(dbUrl, roles);
                            }
                        }
                    }
                }
            }
        }

        /*//查出角色可访问的URL,并且按照URL做为key，角色集合做为值的方式存储角色资源访问权限
        List<Resource> resList = resourceService.findResourceAll();
        if (XaUtil.isNotEmpty(resList)){
            for (Resource resource : resList){
                List<String> roles=new ArrayList<String>();
                roles.add("ADMIN");
                if(XaUtil.isNotEmpty(resource.getResUrl()) && !("/".equals(resource.getResUrl()))){
                    this.urlRoles.put(resource.getResUrl(), roles);
                }
            }
        }*/
    }

}
